package com.roadjava.rbac.security.handler;

import com.roadjava.rbac.bean.res.Result;
import com.roadjava.rbac.security.LoginAttemptService;
import com.roadjava.rbac.util.ResponseUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败(认证处理的过程中抛出了异常)的处理
 *
 */
@Component
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    @Resource
    private LoginAttemptService loginAttemptService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String username = request.getParameter("username");
        loginAttemptService.loginFailed(username);
        // 记录失败

        if (loginAttemptService.isBlocked(username)) {
            Result<String> result = Result.buildFailure("登录失败次数过多，请稍后再试。");
            ResponseUtil.respAppJson(response, result);
        } else {
            Result<String> result = Result.buildFailure("认证失败(用户名或密码不正确)");
            ResponseUtil.respAppJson(response, result);
        }
    }
}

